package com.tiancikeji.zaoke.app.biz.impl;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;

import com.tiancikeji.zaoke.app.biz.OrderBiz;
import com.zaoke.web.bo.order.Order;
import com.zaoke.web.bo.order.PayMode;
import com.zaoke.web.service.order.OrderService;
import com.zaoke.web.service.user.UserService;

public class OrderBizImpl implements OrderBiz {
	
	private OrderService orderService;
	
	private UserService userService;

	public Order getOrderById(long orderid) {
		return orderService.getOrderById(orderid);
	}

	public List<Order> getActiveOrdersByZoneId(long zoneId) {
		List<Order> result = new ArrayList<Order>();
		if(zoneId > 0){
			List<Order> orders = orderService.getActiveOrdersByZoneId(zoneId);
			
			Date now = new Date();
			SimpleDateFormat sdf = new SimpleDateFormat("HH");
			int hour = NumberUtils.toInt(sdf.format(now), 0);
			if(hour >= 20)
				now = DateUtils.addDays(now, 1);
			if(orders != null && orders.size() > 0)
				for(Order order : orders)
					if(order != null && order.getZoneid() == zoneId && ((order.getPayway() == 0 && order.getState() == Order.STATE_UNPAID) || (order.getPayway() >= 0 && order.getState() == Order.STATE_PAID)))
						if(order.getOrderFood() != null && order.getOrderFood().size() > 0 && order.getOrderFood().size() <= 2){
							if(DateUtils.isSameDay(now, order.getBooktime()))
								result.add(order);
						}
		}
		
		return result;
	}

	@Override
	public boolean consumeOrder(Order order) {
		if(order != null && order.getState() != Order.STATE_CANCEL){
			if(order.getPayway() != PayMode.MODE_OFFLINE && (order.getState() == Order.STATE_UNPAID || order.getState() == Order.STATE_UNPAID_EXPIRE))
				return false;
			order.setConsumetime(new Date());
			return orderService.consumeOrder(order);
		}
		return false;
	}

	public OrderService getOrderService() {
		return orderService;
	}

	public void setOrderService(OrderService orderService) {
		this.orderService = orderService;
	}

	public UserService getUserService() {
		return userService;
	}

	public void setUserService(UserService userService) {
		this.userService = userService;
	}
}
